<template>
  <view class="content">
    <nav-bar title="经营数据"></nav-bar>
    <view class="stats-container">
      <view class="stats-card">
        <view class="stats-title">{{ storeName }}</view>
        <view class="stats-grid">
          <view class="stats-item">
            <text class="stats-label">员工数</text>
            <text class="stats-value">{{ stats.staff_count || 0 }}</text>
          </view>
          <view class="stats-item">
            <text class="stats-label">客户数</text>
            <text class="stats-value">{{ stats.customer_count || 0 }}</text>
          </view>
          <view class="stats-item">
            <text class="stats-label">订单数</text>
            <text class="stats-value">{{ stats.order_count || 0 }}</text>
          </view>
          <view class="stats-item">
            <text class="stats-label">总订单金额</text>
            <text class="stats-value">¥{{ (stats.total_order_amount || 0).toFixed(2) }}</text>
          </view>
          <view class="stats-item">
            <text class="stats-label">总充值({{ stats.recharge_count || 0 }}次)</text>
            <text class="stats-value">¥{{ (stats.total_recharge_amount || 0).toFixed(2) }}</text>
          </view>
          <view class="stats-item">
            <text class="stats-label">现金收入({{  stats.per_count || 0 }}次)</text>
            <text class="stats-value">¥{{ (stats.total_per_amount || 0).toFixed(2) }}</text>
          </view>
          <view class="stats-item">
            <text class="stats-label">总成本</text>
            <text class="stats-value">¥{{ (stats.total_cost || 0).toFixed(2) }}</text>
          </view>
          <view class="stats-item">
            <text class="stats-label">净利润</text>
            <text class="stats-value" :style="{ color: netProfitColor }">
              ¥{{ (stats.net_income || 0).toFixed(2) }}
            </text>
          </view>
          <view class="stats-item">
            <text class="stats-label">总提成</text>
            <text class="stats-value">¥{{ (stats.total_commission_cost || 0).toFixed(2) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 添加时间切换Tab -->
    <view class="time-tabs">
      <view class="tab-item" :class="{ active: activeTab === 'day' }" @click="changeTab('day')">日</view>
      <view class="tab-item" :class="{ active: activeTab === 'month' }" @click="changeTab('month')">月</view>
      <view class="tab-item" :class="{ active: activeTab === 'year' }" @click="changeTab('year')">年</view>
      
    </view>
         <!-- 添加分页控件 -->
    <uni-pagination
        :current="pagination.page" 
        :pageSize="pagination.limit"
        :total="pagination.total"
        @change="handlePageChange"
      />
    <!-- 业绩表格 -->
    <view class="performance-table">
      <view class="table-header">
        <text class="header-item">员工姓名</text>
        <text class="header-item">{{ activeTab === 'day' ? '日' : activeTab === 'month' ? '月' : '年' }}</text>
        <text class="header-item">业绩</text>
        <text class="header-item">提成</text>
      </view>
      <view class="table-row" v-for="(item, index) in performanceData" :key="index" @click="handleRowClick(item)">
        <text class="row-item">{{ item.staff_name }}</text>
        <text class="row-item">
          {{ activeTab === 'day' ? formatDayDate(item.consumption_day) :
          activeTab === 'month' ? (item.consumption_month ? formatMonthDate(item.consumption_month) : '') :
            (item.consumption_year ? item.consumption_year + '年' : '') }}
        </text>
        <text class="row-item">¥{{ item.performance.toFixed(2) }}</text>
        <text class="row-item">¥{{ item.commission.toFixed(2) }}</text>
      </view>
    </view>
    <view style="margin-top: 360rpx;"></view>
    <tab-bar />
  </view>
</template>

<script>
import auth from '@/utils/auth.js';
import TabBar from '@/components/tab-bar/tab-bar.vue';
import cardConsumptionsAPI from '@/utils/card_consumptions.js';
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
  components: {
    TabBar,NavBar
  },
  computed: {
    netProfit() {
      return (this.stats.total_recharge_amount || 0) - (this.stats.total_cost || 0);
    },
    netProfitColor() {
      return this.netProfit > 0 ? '#4CD964' : this.netProfit < 0 ? '#DD524D' : '#333';
    }
  },
  data() {
    return {
      pagination: {
        page: 1,
        limit: 10,
        total: 0
      },
      activeTab: 'day', // day/month/year
      performanceData: [], // 业绩数据
      storeName: '',
      storeId: '',
      showCustomNav: true,
      stats: {
        store_count: 0,
        staff_count: 0,
        customer_count: 0,
        order_count: 0,
        total_order_amount: 0,
        recharge_count: 0,
        total_recharge_amount: 0,
        total_cost: 0,
        total_commission_cost: 0
      }
    }
  },
  onLoad(options) {
    this.storeId = options.store_id;
    this.storeName = decodeURIComponent(options.store_name) || '店铺统计';
    this.checkLogin();
  },
  onShow() {
    this.loadStats(); // 添加这行，在页面显示时也刷新数据
    this.fetchPerformanceData();
  },
  methods: {
    handleRowClick(item) {
      // 根据当前选中的tab和数据计算日期范围
      let startDate = '';
      let endDate = '';
      
      if (this.activeTab === 'day') {
        // 日维度：使用当天日期
        const day = String(item.consumption_day);
        const year = day.substring(0, 4);
        const month = day.substring(4, 6);
        const date = day.substring(6, 8);
        startDate = `${year}-${month}-${date}`;
        endDate = startDate;
      } else if (this.activeTab === 'month') {
        // 月维度：使用月份的第一天到最后一天
        const month = String(item.consumption_month);
        const year = month.substring(0, 4);
        const monthNum = month.substring(4, 6);
        startDate = `${year}-${monthNum}-01`;
        const lastDay = new Date(year, monthNum, 0).getDate();
        endDate = `${year}-${monthNum}-${lastDay}`;
      } else {
        // 年维度：使用年份的第一天到最后一天
        const year = item.consumption_year;
        startDate = `${year}-01-01`;
        endDate = `${year}-12-31`;
      }

      // 跳转到明细页面，携带日期参数和用户ID
      console.log('startDate:', startDate, 'endDate:', endDate, 'user_id:', item.staff_id);
      uni.navigateTo({
        url: `/pages/store/my_list?start_date=${startDate}&end_date=${endDate}&user_id=${item.staff_id}`
      });
    },
    handlePageChange(e) {
      this.pagination.page = e.current;
      this.fetchPerformanceData();
    },
    formatMonthDate(month) {
      if (!month) return '';
      const monthStr = month.toString();
      const year = monthStr.substring(0, 4);
      const monthNum = parseInt(monthStr.substring(4, 6));
      return `${year}年${monthNum}月`;
    },
    formatDayDate(day) {
      if (!day) return '';
      const dayStr = day.toString();
      const month = parseInt(dayStr.substring(4, 6));
      const date = parseInt(dayStr.substring(6, 8));
      return `${month}月${date}日`;
    },
    changeTab(tab) {
      this.activeTab = tab;
      this.pagination.page = 1; // 重置到第一页
      this.fetchPerformanceData();
    },

    async fetchPerformanceData() {
      try {
        // 修改为使用params对象传递参数
        const params = {
          store_id: this.storeId,
          type: this.activeTab,
          page: this.pagination.page,
          limit: this.pagination.limit
        };
        const res = await cardConsumptionsAPI.getStaffPerformance(params);
        this.performanceData = res.list || [];
        this.pagination.total = res.pagination.total || 0;
      } catch (e) {
        uni.showToast({
          title: '获取业绩数据失败',
          icon: 'none'
        });
      }
    },
    async checkLogin() {
      if (!auth.getToken()) {
        console.log("--用户未登录--");
        uni.reLaunch({
          url: '/pages/login/index'
        });
        return;
      }

      try {
        const isValid = await auth.valid();
        if (!isValid) {
          console.log("--token已失效--");
          auth.clearTokens();
          uni.reLaunch({
            url: '/pages/login/index'
          });
        } else {
          console.log("--用户已经登录--");
          //this.loadStats();
        }
      } catch (e) {
        console.log("--token验证失败--");
        auth.clearTokens();
        uni.reLaunch({
          url: '/pages/login/index'
        });
      }
    },
    async loadStats() {
      try {
        const res = await cardConsumptionsAPI.getStoreStatistics({
          store_id: this.storeId
        });
        this.stats = res;
      } catch (e) {
        uni.showToast({
          title: '获取统计数据失败',
          icon: 'none'
        });
      }
    },
    navigateBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style>
/* #ifdef H5 */
.content {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* #endif */

/* #ifdef MP-WEIXIN */
.content {
  padding: 30rpx;
  padding-top: 60rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  margin-top: 60rpx;
}

/* #endif */

.stats-container {
  margin-bottom: 120rpx;
}

.stats-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.stats-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  text-align: center;
  text-decoration: underline;
}

.stats-grid {
  display: flex;
  flex-wrap: wrap;
}

.stats-item {
  flex: 1;
  min-width: 33%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
}

.stats-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.stats-value {
  font-size: 36rpx;
  color: #333;
  font-weight: bold;
}

/* 确保自定义导航栏在所有平台都显示 */
.custom-nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background-color: #007AFF;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

/* 添加平台特定样式 */
/* #ifdef H5 */
.custom-nav-bar {
  top: env(safe-area-inset-top);
}

/* #endif */

.container {
  padding-top: 44px;
  padding-bottom: 50px;
}


/* 表格样式 */
.performance-table {
  margin-top: 30rpx;
}

.table-header,
.table-row {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.header-item,
.row-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
}

.header-item {
  font-weight: bold;
  color: #333;
}

.row-item {
  color: #666;
}
</style>

